package net.thetabx.ftdba.activities;

import java.util.List;

import net.thetabx.ftdba.GlobalData;
import net.thetabx.ftdba.R;
import net.thetabx.ftdba.RStatus;
import net.thetabx.ftdba.Shoutbox;
import net.thetabx.ftdba.http.HttpData;
import net.thetabx.ftdba.http.HttpManager;
import net.thetabx.ftdba.objects.Message;
import net.thetabx.ftdba.utils.TextEncoder;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Spanned;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TextView.BufferType;

public class ShoutboxActivity extends Activity {
	static final int LOGIN_REQUEST = 0;
    
    private TextView txtData;
    private EditText edtChatbox;
    private TableLayout tblData;
    private ScrollView scrollView;
    
    private HttpManager http;
    private Boolean sbUpdaterRun = false;
    private Thread shoutboxRefresher;
    private Shoutbox sb;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shoutbox);
        
        edtChatbox = (EditText)findViewById(R.id.edtSbBox);
        tblData = (TableLayout)findViewById(R.id.tblSbData);
        scrollView = (ScrollView)findViewById(R.id.scrollView1);
        
        http = GlobalData.getHttpManager();

        edtChatbox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if(v != edtChatbox || edtChatbox.getText().toString().equals(""))
					return false;
				if(actionId == EditorInfo.IME_NULL || actionId == EditorInfo.IME_ACTION_DONE) {
					sendMessage(edtChatbox.getText().toString());
					edtChatbox.setText("");
					return false;
				}
				return false;
			}
		});
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    	if(shoutboxRefresher != null && shoutboxRefresher.isAlive())
    		sbUpdaterRun = true;
    	else {
    		initShoutboxRefresher();
    		shoutboxRefresher.start();
    	}
    }
    
    @Override
    public void onPause() {
    	super.onPause();
    	sbUpdaterRun = false;
    }

    public void sendMessage(String message) {
    	String encodedMessage = TextEncoder.EncodeText(message);
    	class MessageSender extends AsyncTask<String, Boolean, RStatus> {
    		@Override
    		protected RStatus doInBackground(String... params) {
    			if(http == null)
    				return RStatus.NO_HTTP;
    			
    			HttpData hData = http.send("/?section=COMMUNAUTE&module=mod_shoutbox&ajax=1&mod_ajax=1&shoutbox=1&message=" + params[0] + "&dum=" + params[1]);
    			return hData.getStatus();
    		}
    		@Override
    		protected void onPostExecute(RStatus status) {
    			;
    		}
    	}
    	
    	new MessageSender().execute(encodedMessage, String.valueOf(System.currentTimeMillis()));
    }
    
    public void setDataText(final Spanned str) {
    	txtData.post(new Runnable() {
            public void run() {
            	txtData.setText(str, BufferType.SPANNABLE);
            }
        });
    }
    
    public void addDataText(final List<Message> msgs) {
    	tblData.post(new Runnable() {
            public void run() {
            	/*for(int i = msgs.size() - 1; i >= 0; i--) {
            		Message msg = msgs.get(i);
	            	TableRow row = new TableRow(ShoutboxActivity.this);
	            	row.setTag("msg_" + msg.getId());
	            	
	            	TextView rowData = new TextView(ShoutboxActivity.this);
	            	rowData.setText("[" + msg.getTime() + "] " + msg.getUser() + ": ");
	            	row.addView(rowData);
	            	
	            	TextView rowText = new TextView(ShoutboxActivity.this);
	            	rowText.setText(msg.getText(), BufferType.SPANNABLE);
	            	row.addView(rowText);
	            	
	            	tblData.addView(row);
            	}
            	int messageIdDeleted[] = sb.getMessageIdDeleted();
            	if(messageIdDeleted != null) {
            		for(int i : messageIdDeleted) {
            			tblData.removeView(tblData.findViewWithTag("msg_" + i));
            		}
            	}
            	
            	scrollView.fullScroll(ScrollView.FOCUS_DOWN); */
            	tblData.removeAllViews();
            	for(int i = msgs.size() - 1; i >= 0; i--) {
            		Message msg = msgs.get(i);
	            	TableRow row = new TableRow(ShoutboxActivity.this);
	            	
	            	TextView rowData = new TextView(ShoutboxActivity.this);
	            	rowData.setText(/*"[" + msg.getTime() + "] " + */msg.getUser() + ": ");
	            	row.addView(rowData);
	            	
	            	TextView rowText = new TextView(ShoutboxActivity.this);
	            	rowText.setText(msg.getText(), BufferType.SPANNABLE);
	            	row.addView(rowText);
	            	
	            	tblData.addView(row);
            	}
            	
            	try { Thread.sleep(100); } catch (InterruptedException e) {}
            	scrollView.post(new Runnable() {
                    public void run() {
                    	scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                    }
                });
            }
        });
    }
    
    private void initShoutboxRefresher() {
    	shoutboxRefresher = new Thread(new Runnable() {
            public void run() {
            	sbUpdaterRun = true;
            	sb = new Shoutbox();
            	while(sbUpdaterRun) {
            		sb.pullMessages(http);
            		if(sb.getStatus() == RStatus.ENDED)
            			addDataText(sb.getMessageList());
            			//addDataText(sb.getMessageListNew());
                	//else
                		//display = new SpannableStringBuilder(sb.getStatus().toString());
            		
            		try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
            	}
            }
        });
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
    	menu.findItem(R.id.menu_shoutbox).setVisible(false);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.menu_userstat: {
            	finish();
        		return true;
            }
            case R.id.menu_userlist: {
            	finish();
        		startActivity(new Intent(this, UserlistActivity.class));
        		return true;
            }
            case R.id.menu_torrents: {
            	finish();
        		startActivity(new Intent(this, TorrentsListActivity.class));
        		return true;
            }
            case R.id.menu_options: {
            	finish();
        		startActivity(new Intent(this, OptionsActivity.class));
                return true;
            }
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}
